package hu.blok1.veilingsite.client.gui;

import hu.blok1.veilingsite.client.Veilingsite;
import hu.blok1.veilingsite.client.data.AccountService;
import hu.blok1.veilingsite.client.data.AccountServiceAsync;
import hu.blok1.veilingsite.shared.Address;
import hu.blok1.veilingsite.shared.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class personalPageGUI {
	private VerticalPanel vp, vp2;
	private Veilingsite veilingsite;
	private HorizontalPanel hp;
	private FlexTable userInfo, addressInfo;
	private User user;
	private Address address;
	
	private String oldName;
	private String oldLastName;
	private String oldBankAccount;
	private String oldPhoneNumber;
	private String oldStreet;
	private String oldHouseNumber;
	private String oldPlace;
	private String oldCountry;
	private String oldPostCode;
	
	private TextBox tb_name = new TextBox();
	private TextBox tb_lastname = new TextBox();
	private TextBox tb_email = new TextBox();
	private PasswordTextBox tb_pass1 = new PasswordTextBox();
	private PasswordTextBox tb_pass2 = new PasswordTextBox();
	private TextBox tb_regDate = new TextBox();
	private TextBox tb_userT = new TextBox();
	private TextBox tb_bankaccount = new TextBox();
	private TextBox tb_credits = new TextBox();
	private TextBox tb_phonenumber = new TextBox();
	
	private TextBox tb_street = new TextBox();
	private TextBox tb_housenumber = new TextBox();
	private TextBox tb_place = new TextBox();
	private TextBox tb_country = new TextBox();
	private TextBox tb_postCode = new TextBox();
	
	private Button b_save = new Button("Sla op");
	private Button b_reset = new Button("Terug naar huidige waarden");
	private Button b_changePassword = new Button("Verander Wachtwoord");
	
	private DialogBox dialog = new DialogBox();
	private Button d_closeButton = new Button("Annuleren");
	private Button d_submitButton = new Button("Verander wachtwoord");
	
	private Label errorLabel = new Label();
	
	private DateTimeFormat dtf;
	
	private final AccountServiceAsync accountService = GWT.create(AccountService.class);
	
	public personalPageGUI(Veilingsite vs){
		veilingsite = vs;
		user = veilingsite.getUser();
		address = user.getAddress();
		vp = veilingsite.getMainPanel();
		
		if(user.isLoggedIn()){
			init();
		}else{
			vp.clear();
			History.newItem("login");
		}
	}
	
	public void init(){
		vp.clear();
		veilingsite.reloadRightMenu();
		dialog.setText("Verander Uw Wachtwoord");
		dialog.setAnimationEnabled(true);
		VerticalPanel dialogVPanel = new VerticalPanel();
		HorizontalPanel dialogHPanelPassBox1 = new HorizontalPanel();
		dialogHPanelPassBox1.setWidth(100 + "%");
		dialogHPanelPassBox1.add(new Label("Nieuw wachtwoord:"));
		dialogHPanelPassBox1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		dialogHPanelPassBox1.add(tb_pass1);
		dialogVPanel.add(dialogHPanelPassBox1);
		HorizontalPanel dialogHPanelPassBox2 = new HorizontalPanel();
		dialogHPanelPassBox2.setWidth(100 + "%");
		dialogHPanelPassBox2.add(new Label("Nieuw wachtwoord (nogmaals):"));
		dialogHPanelPassBox2.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		dialogHPanelPassBox2.add(tb_pass2);
		dialogVPanel.add(dialogHPanelPassBox2);
		HorizontalPanel dialogHPanelButtons = new HorizontalPanel();
		dialogHPanelButtons.setWidth(100 + "%");
		dialogHPanelButtons.add(d_submitButton);
		dialogHPanelButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		dialogHPanelButtons.add(d_closeButton);
		dialogVPanel.add(dialogHPanelButtons);
		dialog.setWidget(dialogVPanel);
		
		d_closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialog.hide();
				tb_pass1.setText("");
				tb_pass2.setText("");
			}
		});
		
		VerticalPanel testPanel = new VerticalPanel();
		testPanel.add(new Label("test"));
		testPanel.setStylePrimaryName("test");
		hp = new HorizontalPanel();
		vp2 = new VerticalPanel();
		
		dtf = DateTimeFormat.getFormat("E, dd MMM yyyy HH:mm:ss");
		
		String registerDate = "";
		if(user.getRegisterDate() != null){
			registerDate = dtf.format(user.getRegisterDate());
		}
		
		b_save.addClickHandler(click);
		b_reset.addClickHandler(click);
		b_changePassword.addClickHandler(click);
		
		tb_name.setText(user.getName());
		tb_lastname.setText(user.getLastName());
		tb_email.setText(user.getEmail());
		tb_email.setEnabled(false);
		tb_regDate.setText(registerDate);
		tb_regDate.setEnabled(false);
		tb_userT.setText(user.getUserType());
		tb_userT.setEnabled(false);
		tb_bankaccount.setText(user.getBankAccount());
		tb_credits.setText(user.getCredits() + "");
		tb_credits.setEnabled(false);
		tb_phonenumber.setText(address.getPhoneNumber());
		d_submitButton.addClickHandler(click);
		
		
		int row = 0;
		userInfo = new FlexTable();
		userInfo.setText(row, 0, "Gebruikers Informatie");
		row++;
		userInfo.setText(row, 0, "Voornaam:");
		userInfo.setWidget(row, 1, tb_name);
		row++;
		userInfo.setText(row, 0, "Achternaam:");
		userInfo.setWidget(row, 1, tb_lastname);
		row++;
		userInfo.setText(row, 0, "E-mailadres:");
		userInfo.setWidget(row, 1, tb_email);
		row++;
		userInfo.setText(row, 0, "Wachtwoord:");
		userInfo.setWidget(row, 1, b_changePassword);
		row++;
		userInfo.setText(row, 0, "Registratie datum:");
		userInfo.setWidget(row, 1, tb_regDate);
		row++;
		userInfo.setText(row, 0, "Type gebruiker:");
		userInfo.setWidget(row, 1, tb_userT);
		row++;
		userInfo.setText(row, 0, "Bankrekening Nummer:");
		userInfo.setWidget(row, 1, tb_bankaccount);
		row++;
		userInfo.setText(row, 0, "Aantal Credits:");
		userInfo.setWidget(row, 1, tb_credits);
		row++;
		userInfo.setText(row, 0, "Telefoon nummer:");
		userInfo.setWidget(row, 1, tb_phonenumber);
		row++;
		userInfo.setWidget(row, 1, b_save);
		
		tb_street.setText(address.getStreet());
		tb_housenumber.setText(address.getHouseNumber() + "");
		tb_place.setText(address.getCity());
		tb_country.setText(address.getCountry());
		tb_postCode.setText(address.getPostCode());
		
		addressInfo = new FlexTable();
		int row2 = 0;
		addressInfo.setText(row2, 0, "Adres Gegevens");
		row2++;
		addressInfo.setText(row2, 0, "Straatnaam:");
		addressInfo.setWidget(row2, 1, tb_street);
		row2++;
		addressInfo.setText(row2, 0, "Huisnummer:");
		addressInfo.setWidget(row2, 1, tb_housenumber);
		row2++;
		addressInfo.setText(row2, 0, "Postcode:");
		addressInfo.setWidget(row2, 1, tb_postCode);
		row2++;
		addressInfo.setText(row2, 0, "Plaats:");
		addressInfo.setWidget(row2, 1, tb_place);
		row2++;
		addressInfo.setText(row2, 0, "Land:");
		addressInfo.setWidget(row2, 1, tb_country);
		while(row >= row2){
			row2++;
			addressInfo.setHTML(row2, 0, "&nbsp;");
//			addressInfo.setText(row2, 0, "&nbsp;");
		}
		addressInfo.setWidget(row2, 0, b_reset);
		hp.add(userInfo);
		hp.add(addressInfo);
		userInfo.setWidth(350 + "px");
		addressInfo.setWidth(350 + "px");
		vp2.add(hp);
		vp2.setSpacing(10);
		vp2.add(errorLabel);
		vp.add(vp2);
	}
	
	ClickHandler click = new ClickHandler(){
		public void onClick(ClickEvent event) {
			if(event.getSource() == b_reset){
				reset();
			}
			if(event.getSource() == b_save){
				performUpdate();
			}
			if(event.getSource() == b_changePassword){
				dialog.center();
			}
			if(event.getSource() == d_submitButton){
				changePassword();
			}
			
		}
	};
	
	public void reset(){
		tb_name.setText(user.getName());
		tb_lastname.setText(user.getLastName());
		tb_email.setText(user.getEmail());
		if(user.getRegisterDate() != null){
			tb_regDate.setText(dtf.format(user.getRegisterDate()) + "");
		}else{
			tb_regDate.setText("");
		}
		tb_userT.setText(user.getUserType());
		tb_bankaccount.setText(user.getBankAccount());
		tb_credits.setText(user.getCredits() + "");
		tb_phonenumber.setText(address.getPhoneNumber());
		tb_street.setText(address.getStreet());
		tb_housenumber.setText(address.getHouseNumber() + "");
		tb_place.setText(address.getCity());
		tb_country.setText(address.getCountry());
		tb_postCode.setText(address.getPostCode());
	}
	
	public void performUpdate(){
		boolean changes = false;
		oldName = user.getName();
		oldLastName = user.getLastName();
		oldBankAccount = user.getBankAccount();
		oldPhoneNumber = address.getPhoneNumber();
		oldStreet = address.getStreet();
		oldHouseNumber = address.getHouseNumber();
		oldPlace = address.getCity();
		oldCountry = address.getCountry();
		oldPostCode = address.getPostCode();
		
		if(!tb_name.getText().equals("")){
			if(!oldName.equals(tb_name.getText())){
				if(tb_name.getText().matches("^[a-zA-Z]{3,100}")){
					user.setName(tb_name.getText());
					changes = true;
				}else{
					errorLabel.setText("Ongeldige naam");
				}
			}
		}
		if(!tb_lastname.getText().equals("")){
			if(!oldLastName.equals(tb_lastname.getText())){
				if(tb_lastname.getText().matches("^[a-zA-Z]{3,100}")){
					user.setLastName(tb_lastname.getText());
					changes = true;
				}
			}
		}
		if(!tb_bankaccount.getText().equals("")){
			if(!oldBankAccount.equals(tb_bankaccount.getText())){
				if(tb_bankaccount.getText().matches("^(0-9){8,10}")){
					user.setBankAccount(tb_bankaccount.getText());
					changes = true;
				}
			}
		}
		if(!tb_phonenumber.getText().equals("")){
			if(tb_phonenumber.getText().matches("([0]{1}[6]{1}[-\\s]*[1-9]{1}[\\s]*([0-9]{1}[\\s]*){7})|([0]{1}[1-9]{1}[0-9]{1}[0-9]{1}[-\\s]*[1-9]{1}[\\s]*([0-9]{1}[\\s]*){5})|([0]{1}[1-9]{1}[0-9]{1}[-\\s]*[1-9]{1}[\\s]*([0-9]{1}[\\s]*){6})")){
				if(!oldPhoneNumber.equals(tb_phonenumber.getText())){
					address.setPhoneNumber(tb_phonenumber.getText());
					changes = true;
				}
			}else{
				errorLabel.setText("Ongeldig telefoonnummer");
			}
		}
		if(!tb_street.getText().equals("")){
			if(!oldStreet.equals(tb_street.getText())){
				address.setStreet(tb_street.getText());
				changes = true;
			}
		}
		if(!tb_housenumber.getText().equals("")){
			if(tb_housenumber.getText().matches("^[0-9]{1,5}$")){
				if(!oldHouseNumber.equals(tb_housenumber.getText())){
					address.setHouseNumber(tb_housenumber.getText());
					changes = true;
				}
			}else{
				errorLabel.setText("Ongeldig huisnummer");
			}
		}
		if(!tb_place.getText().equals("")){
			if(!oldPlace.equals(tb_place.getText())){
				address.setCity(tb_place.getText());
				changes = true;
			}
		}
		if(!tb_country.getText().equals("")){
			if(!oldCountry.equals(tb_country.getText())){
				address.setCountry(tb_country.getText());
				changes = true;
			}
		}
		if(!tb_postCode.getText().equals("")){
			if(!oldPostCode.equals(tb_postCode.getText())){
				address.setPostCode(tb_postCode.getText());
				changes = true;
			}
		}
		if(changes){
			accountService.updateUser(user, address, new AsyncCallback<Boolean>(){
				public void onFailure(Throwable caught) {
					Window.alert("And yet again, no damn connection wiz da servah!");
					user.setName(oldName);
					user.setLastName(oldLastName);
					user.setBankAccount(oldBankAccount);
					address.setStreet(oldStreet);
					address.setHouseNumber(oldHouseNumber);
					address.setCity(oldPlace);
					address.setCountry(oldCountry);
					address.setPhoneNumber(oldPhoneNumber);
					address.setPostCode(oldPostCode);
					reset();
				}
	
				public void onSuccess(Boolean result) {
					if(result){
						errorLabel.setText(errorLabel.getText() + " Succesfully updated");
						reset();
						veilingsite.reloadHeader();
					}else{
						Window.alert("It seems to be there is an error on the server, so your changes has been undone.");
						user.setName(oldName);
						user.setLastName(oldLastName);
						user.setBankAccount(oldBankAccount);
						address.setStreet(oldStreet);
						address.setHouseNumber(oldHouseNumber);
						address.setCity(oldPlace);
						address.setCountry(oldCountry);
						address.setPhoneNumber(oldPhoneNumber);
						address.setPostCode(oldPostCode);
						reset();
					}
				}
			});
		}else{
			errorLabel.setText(errorLabel.getText() + " - No changes made");
		}
	}
	
	public void changePassword(){
		if(!tb_pass1.getText().equals("") && !tb_pass2.getText().equals("")){
			if(tb_pass1.getText().equals(tb_pass2.getText())){
				user.setPassword(tb_pass1.getText());
				accountService.changePassword(user, new AsyncCallback<Boolean>(){
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Helaas zijn er op dit moment problemen met de server, probeer het later nog eens.");
					}

					@Override
					public void onSuccess(Boolean result) {
						dialog.hide();
						Window.alert("Wachtwoord gewijzigd!");
					}
				});
			}
		}
	}
}
